package com.ytclub.subject.domain.handle;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.ytclub.subject.common.enums.IsDeletedFlagEnum;
import com.ytclub.subject.common.enums.SubjectInfoTypeEnum;
import com.ytclub.subject.domain.convert.RadioSubjectConverter;
import com.ytclub.subject.domain.entity.SubjectAnswerBO;
import com.ytclub.subject.domain.entity.SubjectInfoBO;
import com.ytclub.subject.domain.entity.SubjectOptionBO;
import com.ytclub.subject.infra.basic.entity.SubjectRadio;
import com.ytclub.subject.infra.basic.service.SubjectRadioService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * 单选题Handle
 *
 * @author: HuangQi
 * @date: Created in 21:55 2023/12/20
 * @description:
 */
@Slf4j
@Component
public class RadioTypeHandler implements SubjectTypeHandler {

    @Resource
    private SubjectRadioService subjectRadioService;

    @Override
    public SubjectInfoTypeEnum getHandlerType() {
        return SubjectInfoTypeEnum.RADIO;
    }

    @Override
    public void add(SubjectInfoBO subjectInfoBO) {
        // 单选题目的插入
        if (log.isInfoEnabled()) {
            log.info("RadioTypeHandler.add.bo:{}", JSON.toJSONString(subjectInfoBO));
        }

        // 参数校验
        Preconditions.checkNotNull(CollectionUtils.isEmpty(subjectInfoBO.getOptionList()), "单选题目的选项不能为空");
        Preconditions.checkNotNull(subjectInfoBO.getSubjectAnswer(), "单选题目答案不能为空");
        Preconditions.checkNotNull(subjectInfoBO.getSubjectParse(), "单选题目解析不能为空");

        // 类型转换
        List<SubjectRadio> subjectRadioList = new LinkedList<>();
        subjectInfoBO.getOptionList().forEach(Option -> {
            SubjectRadio subjectRadio = RadioSubjectConverter.INSTANCE.convertBoToEntity(Option);
            subjectRadio.setSubjectId(subjectInfoBO.getId());
            subjectRadio.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
            subjectRadioList.add(subjectRadio);
        });

        // 数据插入
        subjectRadioService.batchInsert(subjectRadioList);
    }

    /**
     * 根据题目id查询题目答案
     *
     * @param subjectId 题目id
     * @return 题目答案
     */
    @Override
    public SubjectOptionBO query(Long subjectId) {
        // 根据单选题题目id查询答案
        SubjectRadio subjectRadio = new SubjectRadio();
        subjectRadio.setSubjectId(subjectId);
        List<SubjectRadio> result = subjectRadioService.queryByConditon(subjectRadio);

        // 返回单选题题目答案
        List<SubjectAnswerBO> subjectAnswerBOList = RadioSubjectConverter.INSTANCE.convertEntityToBoList(result);
        SubjectOptionBO subjectOptionBO = new SubjectOptionBO();
        subjectOptionBO.setOptionList(subjectAnswerBOList);
        return subjectOptionBO;
    }
}
